package com.luo.bbs.front.webapi.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.luo.bbs.front.webapi.mapper.CollectMapper;
import com.example.bbs.front.service.ICollectService;
import com.luo.bbs.front.webapi.pojo.UserLoginPrincipal;
import com.luo.common.exception.BBSServiceException;
import com.luo.common.restful.ResponseCode;
import com.luo.pojo.Collect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bin.cn
 * @since 2023-01-19
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {

    @Autowired
    private CollectMapper collectMapper;

    @Override
    public Integer countByUser() {
        Integer count = collectMapper.selectCount(
                new QueryWrapper<Collect>().eq("user_id", getUserId())
        );
        return count;
    }

    public UserLoginPrincipal getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginPrincipal principal = (UserLoginPrincipal) authentication.getPrincipal();
        if (principal == null) {
            throw new BBSServiceException(ResponseCode.UNAUTHORIZED, "未登录！");
        }
        return principal;
    }

    public Integer getUserId() {
        if (getUserInfo() == null) {
            return null;
        }
        return getUserInfo().getId();
    }
}
